# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
# from pymongo import MongoClient
from django.core.cache import cache
from pymongo import MongoClient
from alldata.tools.w_other import Mysql

import threading
import configparser
import re

class obtain_data(object):
    def __init__(self):
        self.config_file = r'conf\config.ini'
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file, encoding="utf-8")

    def mysql_con(self):
        global other_sum
        other_sum = []
        # host = self.config.get('mysql', 'host')
        # port = self.config.get('mysql', 'port')
        # dbname = self.config.get('mysql', 'dbname')
        # user = self.config.get('mysql', 'username')
        # pwd = self.config.get('mysql', 'passwd')
        # db = pymysql.connect(host, user, pwd, dbname, charset='utf8')
        # cursor = db.cursor()
        mysqlcon = Mysql()
        self.shop_user_sum(mysqlcon)
        self.mongodb_con()
        # cursor.close()
        return other_sum

    def mongodb_con(self):
        try:
            # 认证（密码无特殊符号）
            obd_data = {}
            host = self.config.get('mongodb', 'host')
            port = self.config.get('mongodb', 'port')
            dbname = self.config.get('mongodb', 'dbname')
            user = self.config.get('mongodb', 'username')
            pwd = self.config.get('mongodb', 'passwd')
            # mongo_client = MongoClient('mongodb://'+user+':'+pwd+'@'+host+':'+port+'/'+dbname+'?')
            # 认证（密码含特殊符号）
            mongo_client = MongoClient(host)
            mongo_client[dbname].authenticate(user, pwd, dbname)
            # 连接到库：kafkadb
            newdb = mongo_client.cars
            obd_data['OBD用户'] = newdb.car.find({"isDeleted": 0, "obdId": {'$ne': None}}).count()
            other_sum.append(obd_data)
        except:
            print('mongodb数据库连接不上')



    def shop_user_sum(self, cursor):
        shop_sql = "SELECT COUNT(1) FROM `s_shop` WHERE isUsing = 1 AND shopState = 1 AND isDelete=0"
        user_sql = "SELECT COUNT(1) FROM y_info_account WHERE isDelete = 0"
        shop_data = cursor.getOne(shop_sql)
        user_data = cursor.getOne(user_sql)
        shop_user_data = {}
        try:
            shop_user_data['店铺总量'] = shop_data[0]
            shop_user_data['用户总量'] = user_data[0]
            other_sum.append(shop_user_data)
        except:
            print('店铺总量或用户总量数据缺失')


